package cn.wu.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.dto.DishDto;
import cn.wu.reggie.entity.Category;
import cn.wu.reggie.entity.Dish;
import cn.wu.reggie.mapper.DishDtoMapper;
import cn.wu.reggie.query.DishQuery;
import cn.wu.reggie.service.ICategoryService;
import cn.wu.reggie.service.IDishDtoService;
import cn.wu.reggie.service.IDishService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DishDtoServiceImpl extends ServiceImpl<DishDtoMapper, DishDto> implements IDishDtoService {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IDishService dishService;


    @Override
    public Page<DishDto> findByPage(DishQuery qo) {
        // 1 查询菜品分类列表 把list转成map  分类id 分类名称
        QueryWrapper<Category> categoryWrapper = new QueryWrapper<>();
        categoryWrapper.eq("type", 1);
        List<Category> categoryList = categoryService.getBaseMapper().selectList(categoryWrapper);
        Map<Long, String> categoryMap = new HashMap<>();
        categoryList.forEach(c -> {
            categoryMap.put(c.getId(), c.getName());
        });
        // 2 根据名称查询所有
        QueryWrapper<Dish> dishWrapper = new QueryWrapper<>();
        dishWrapper.like(qo.getName()!=null,"name", qo.getName());
        List<Dish> dishList = dishService.getBaseMapper().selectList(dishWrapper);

        // 3 新建一个DtoList 遍历查询的结合 将dish封装成dishDto 且给dto设置分类名称 将dto放入dtoList中
        List<DishDto> dtoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(dishList)) {
            dishList.forEach(dish -> {
                DishDto dto = new DishDto();
                // 拷贝 设置分类名称
                BeanUtils.copyProperties(dish, dto);
                dto.setCategoryName(categoryMap.get(dish.getCategoryId()));
                dtoList.add(dto);
            });
        }
        // 4 设置分页参数
        Page<DishDto> dishPage = new Page<>(qo.getPage(), qo.getPageSize());
        QueryWrapper<DishDto> DishDtoWrapper = new QueryWrapper<>();
        return page(dishPage, DishDtoWrapper);
    }

}
